import axios from 'axios'
import router from '@/router'
import { useUserStore } from '@/stores'
const baseURL = '/api'

const instance = axios.create({
  // 1. 基础地址，超时时间
  baseURL,
  timeout: 10000
})

instance.interceptors.request.use(
  (config) => {
    // config.headers['Content-Type'] = 'application/json;charset=utf-8'
    // 2. 携带token
    const userStore = useUserStore()
    if (userStore.user.token) {
      config.headers['om-token'] = userStore.token
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    // 3. 处理业务失败
    // 4. 摘取核心响应数据
    let response = res.data
    if (Number(response.code) === 200) {
      if (response?.successMsg) {
        ElMessage.success(response?.successMsg)
      }
      return Promise.resolve(response)
    }
    // 处理业务失败，抛出异常
    ElMessage.error(response.msg || '服务异常')
    return Promise.reject(response)
  },
  (err) => {
    // 5. 处理401错误
    // 特殊情况 => token过期，权限不足
    if (err.response?.status === 401) {
      router.push('/login')
    }
    // 错误的默认情况
    ElMessage.error(err.response?.data.msg || '服务异常')
    return Promise.reject(err)
  }
)

export default instance

export { baseURL }
